﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using PerformanceDude.MSBuildShellExtension.Common;
using StringResources = PerformanceDude.MSBuildShellExtension.Loggers.ErrorListLogger.Properties.Resources;
using Microsoft.Build.Framework;

/*
 * Copyright (c) 2007-2012, Thomas Ardal (thomasardalatgmail.com), Lex Li (supportatlextm.com), Rami Abughazaleh (rami.abughazalehatgmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Thomas Ardal nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
namespace PerformanceDude.MSBuildShellExtension.Loggers.ErrorListLogger
{
    /// <summary>
    /// Interaction logic for BuildOutputDialog.xaml
    /// </summary>
    public partial class BuildOutputDialog : Window
    {
        private ConfigurationSettings Settings;
        private BuildOutputModel OutputMessages = new BuildOutputModel();

        public BuildOutputDialog(ConfigurationSettings settings, MSBuildErrorListLogger logger)
        {
            //for debugging purposes
            //System.Diagnostics.Debugger.Launch();

            this.Settings = settings;
            this.WindowStartupLocation = this.Settings.WindowStartupLocation;
            this.Topmost = this.Settings.Topmost;
            this.Height = this.Settings.Height;
            this.Width = this.Settings.Width;
            this.WindowState = this.Settings.WindowState;

            if (this.WindowStartupLocation == WindowStartupLocation.Manual)
            {
                this.Left = this.Settings.Left;
                this.Top = this.Settings.Top;
            }

            InitializeComponent();

            this.btnErrors.IsChecked = this.Settings.ShowErrors;
            this.btnWarnings.IsChecked = this.Settings.ShowWarnings;
            this.btnMessages.IsChecked = this.Settings.ShowMessages;

            logger.BuildStarted += OnBuildStarted;
            logger.BuildFinished += OnBuildFinished;
            logger.Message += OnMessage;
            logger.Warning += OnWarning;
            logger.Error += OnError;

            //default settings
            this.btnErrors.IsChecked = this.Settings.ShowErrors;
            this.btnWarnings.IsChecked = this.Settings.ShowWarnings;
            this.btnMessages.IsChecked = this.Settings.ShowMessages;

            BindData();

            logger.pool.Release();
        }

        private void BindData()
        {
            Dispatcher.BeginInvoke(new Action(() => {
                this.dgOutputMessages.ItemsSource = this.OutputMessages.Messages
                    .Where(x => (btnMessages.IsChecked.Value && x.Level == Level.Info)
                    || (btnWarnings.IsChecked.Value && x.Level == Level.Warning)
                    || (btnErrors.IsChecked.Value && x.Level == Level.Error));

                this.tbErrors.Text = string.Format("{0} Errors", this.OutputMessages.Messages.Count(x => x.Level == Level.Error));
                this.tbWarnings.Text = string.Format("{0} Warnings", this.OutputMessages.Messages.Count(x => x.Level == Level.Warning));
                this.tbMessages.Text = string.Format("{0} Messages", this.OutputMessages.Messages.Count(x => x.Level == Level.Info));
            }));
        }

        private void dgOutputMessages_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
        {
            e.Handled = true;
        }

        private void OnBuildStarted()
        {
            SetStatusText("Building...");
        }

        private void OnBuildFinished(bool succeeded)
        {
            DispatcherHelper.InvokeDispatcher(this, () =>
            {
                if (succeeded && this.Settings.CloseWindowsOnSuccessfulBuild)
                {
                    this.Close();
                }
                else if (!succeeded && (this.Settings.ShowOutputWindowOnlyIfBuildFails))
                {
                    DispatcherHelper.InvokeDispatcher(this, () =>
                    {
                        this.Visibility = Visibility.Visible;
                    });
                }

                if (!this.Settings.CloseWindowsOnSuccessfulBuild)
                {
                    int errors = this.OutputMessages.Messages.Count(x => x.Level == Level.Error);
                    int warnings = this.OutputMessages.Messages.Count(x => x.Level == Level.Warning);

                    if (succeeded)
                    {
                        if ((errors == 0) && (warnings == 0))
                        {
                            SetStatusText("Build succeeded");
                        }
                        else
                        {
                            SetStatusText(string.Format(CultureInfo.InvariantCulture,
                                "Build succeeded - {0} warning(s)",
                                warnings));
                        }
                    }
                    else
                    {
                        if ((errors == 0) && (warnings == 0))
                        {
                            SetStatusText("Build failed");
                        }
                        else
                        {
                            SetStatusText(string.Format(CultureInfo.InvariantCulture,
                                "Build failed - {0} error(s), {1} warning(s)",
                                errors, warnings));
                        }
                    }

                    if (this.Settings.FlashWindowWhenFinished)
                    {
                        FlashWindow.Flash(this);
                    }
                }
            });
        }

        private void OnError(string buildFile, MSBuildErrorListLogger logger, BuildErrorEventArgs args)
        {
            AddMessage(Level.Error, buildFile, logger, args);
        }

        private void OnWarning(string buildFile, MSBuildErrorListLogger logger, BuildWarningEventArgs args)
        {
            AddMessage(Level.Warning, buildFile, logger, args);
        }

        private void OnMessage(string buildFile, MSBuildErrorListLogger logger, BuildMessageEventArgs args)
        {
            AddMessage(Level.Info, buildFile, logger, args);
        }

        private void AddMessage(Level level, string buildFile, MSBuildErrorListLogger logger, BuildEventArgs args)
        {
            Dispatcher.BeginInvoke(new Action(() => {

                bool addMessageToErrorList = true;

                OutputMessage outputMessage = new OutputMessage(this.OutputMessages.Messages.Count + 1, level, buildFile, args.Message);

                if (string.IsNullOrEmpty(args.Message))
                {
                    addMessageToErrorList = false;
                }
                else if (args is BuildMessageEventArgs)
                {
                    BuildMessageEventArgs buildMessageEventArgs = args as BuildMessageEventArgs;

                    if (buildMessageEventArgs.Importance != MessageImportance.High)
                    {
                        addMessageToErrorList = false;
                    }

                    // BuildMessageEventArgs adds Importance to BuildEventArgs
                    // Let's take account of the verbosity setting we've been passed in deciding whether to log the message or not
                    if (((buildMessageEventArgs.Importance == MessageImportance.High && logger.IsVerbosityAtLeast(LoggerVerbosity.Minimal))
                        || (buildMessageEventArgs.Importance == MessageImportance.Normal && logger.IsVerbosityAtLeast(LoggerVerbosity.Normal))
                        || (((buildMessageEventArgs.Importance == MessageImportance.Low) || (buildMessageEventArgs.SenderName == "VCBuild"))
                        && logger.IsVerbosityAtLeast(LoggerVerbosity.Detailed)))
                        && (buildMessageEventArgs.SenderName != "Message"))
                    //BuildEventContext is only available for MSBuild v3.5+
                    //&& (buildMessageEventArgs.BuildEventContext.TargetId > 0)
                    //&& (buildMessageEventArgs.BuildEventContext.TaskId > 0)
                    //&& (buildMessageEventArgs.BuildEventContext.NodeId == 0)
                    {
                        AddOutputMessage(args.Message);
                    }
                }
                else if (args is BuildErrorEventArgs)
                {
                    BuildErrorEventArgs buildErrorEventArgs = args as BuildErrorEventArgs;

                    AddOutputMessage(logger.FormatErrorEvent(buildErrorEventArgs));

                    outputMessage.File = buildErrorEventArgs.File;
                    outputMessage.Line = buildErrorEventArgs.LineNumber;
                    outputMessage.Column = buildErrorEventArgs.ColumnNumber;
                }
                else if (args is BuildWarningEventArgs)
                {
                    BuildWarningEventArgs buildWarningEventArgs = args as BuildWarningEventArgs;

                    AddOutputMessage(logger.FormatWarningEvent(buildWarningEventArgs));

                    outputMessage.File = buildWarningEventArgs.File;
                    outputMessage.Line = buildWarningEventArgs.LineNumber;
                    outputMessage.Column = buildWarningEventArgs.ColumnNumber;
                }

                if (addMessageToErrorList)
                {
                    this.OutputMessages.Messages.Add(outputMessage);

                    BindData();

                    if (dgOutputMessages.Items.Count > 0)
                    {
                        var border = VisualTreeHelper.GetChild(dgOutputMessages, 0) as Decorator;
                        if (border != null)
                        {
                            var scroll = border.Child as ScrollViewer;
                            if (scroll != null) scroll.ScrollToEnd();
                        }
                    }
                }
            }));
        }

        private void AddOutputMessage(string message)
        {
            if (!string.IsNullOrEmpty(this.tbOutput.Text))
            {
                this.tbOutput.Text += Environment.NewLine;
            }

            this.tbOutput.Text += message;
        }

        private void SetStatusText(string message)
        {
            Dispatcher.BeginInvoke(new Action(() => {
                tbStatusBar.Text = message;
            }));
        }

        private void btnErrors_Checked(object sender, RoutedEventArgs e)
        {
            BindData();
        }

        private void btnWarnings_Checked(object sender, RoutedEventArgs e)
        {
            BindData();
        }

        private void btnMessages_Checked(object sender, RoutedEventArgs e)
        {
            BindData();
        }

        private void dgOutputMessages_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            object selectedItem = dgOutputMessages.SelectedItem;

            if ((e.LeftButton == MouseButtonState.Pressed)
                && (selectedItem != null))
            {
                OutputMessage outputMessage = selectedItem as OutputMessage;
                string filename = outputMessage.File;
                string buildFile = outputMessage.Project;

                // Return if double clicked on item with no filename specified (could be messages)
                // Also return if build project has not been set.
                if (string.IsNullOrEmpty(filename))
                {
                    MessageBox.Show(StringResources.filename_could_not_be_resolved);
                    return;
                }

                if (string.IsNullOrEmpty(buildFile))
                {
                    MessageBox.Show(StringResources.build_project_could_not_be_resolved);
                    return;
                }

                // Remove directories from filename (example: Properties\AssemblyInfo.cs -> AssemblyInfo.cs)
                string root = buildFile.Substring(0, buildFile.LastIndexOf("\\"));
                int index = filename.LastIndexOf("\\");
                if (index != -1)
                {
                    filename = filename.Substring(index + 1);
                }

                // Get full name of file (example: AssemblyInfo.cs -> c:\projects\test\properties\AssemblyInfo.cs)
                DirectoryInfo rootDirectory = new DirectoryInfo(root);
                FileInfo[] files = rootDirectory.GetFiles(filename, SearchOption.AllDirectories);
                if (files.Length == 0)
                {
                    MessageBox.Show(StringResources.could_not_find_absolute_path);
                    return;
                }

                try
                {
                    Process.Start(files[0].FullName);
                }
                catch (Win32Exception ex)
                {
                    //ignore Win32Exception if the associated program (ex. VSLauncher.exe) is configured to run as Administrator
                    if ((ex.NativeErrorCode != 1223 /*user canceled elevation prompt*/)
                        && (ex.NativeErrorCode != 1156 /*DDE fails if msbuild.exe is not run as an elevated process*/))
                    {
                        throw;
                    }
                }
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.Settings.SaveWindowLocation)
            {
                this.Settings.Top = this.Top;
                this.Settings.Left = this.Left;
                this.Settings.Height = this.Height;
                this.Settings.Width = this.Width;
                this.Settings.Save();
            }
        }
    }
}
